import {
  ORDER_CREATE_REQUEST,
  ORDER_CREATE_SUCCESS,
  ORDER_CREATE_FAIL,
  ORDER_DETAILS_REQUEST,
  ORDER_DETAILS_SUCCESS,
  ORDER_DETAILS_FAIL,
  ORDER_LIST_REQUEST,
  ORDER_LIST_SUCCESS,
  ORDER_LIST_FAIL,
  ORDER_PAY_REQUEST,
  ORDER_PAY_SUCCESS,
  ORDER_PAY_FAIL,
  ORDER_PAY_RESET,
  ORDER_LIST_MY_REQUEST,
  ORDER_LIST_MY_SUCCESS,
  ORDER_LIST_MY_FAIL,
  ORDER_DELIVER_REQUEST,
  ORDER_DELIVER_SUCCESS,
  ORDER_DELIVER_FAIL,
  ORDER_DELIVER_RESET,
} from "../constants/orderConstants";
import axios from "axios";
import { logout } from "../actions/userActions";
import { CART_CLEAR_ITEMS } from "../constants/cartConstants";

//创建订单
export const createOrder = (order) => async (dispatch, getState) => {
  try {
    dispatch({ type: ORDER_CREATE_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    //创建订单
    const { data } = await axios.post(`/api/orders`, order, config);

    //创建成功，传输数据到reducer
    dispatch({ type: ORDER_CREATE_SUCCESS, payload: data });
    //清空购物车
    dispatch({ type: CART_CLEAR_ITEMS });
  } catch (error) {
    //创建失败
    dispatch({
      type: ORDER_CREATE_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//获取单个订单
export const getOrderDetails = (id) => async (dispatch, getState) => {
  try {
    dispatch({ type: ORDER_DETAILS_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    //获取订单
    const { data } = await axios.get(`/api/orders/${id}`, config);

    //获取成功，传输数据到reducer
    dispatch({ type: ORDER_DETAILS_SUCCESS, payload: data });
  } catch (error) {
    //获取失败
    dispatch({
      type: ORDER_DETAILS_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//获取所有订单
export const listOrders = () => async (dispatch, getState) => {
  try {
    dispatch({ type: ORDER_LIST_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    //获取订单
    const { data } = await axios.get(`/api/orders`, config);

    //获取成功，传输数据到reducer
    dispatch({ type: ORDER_LIST_SUCCESS, payload: data });
  } catch (error) {
    //获取失败
    dispatch({
      type: ORDER_LIST_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//更新订单支付状态
export const payOrder = (orderId, paymentResult) => async (
  dispatch,
  getState
) => {
  try {
    dispatch({ type: ORDER_PAY_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    //更新订单
    const { data } = await axios.put(
      `/api/orders/${orderId}/pay`,
      paymentResult,
      config
    );

    //更新成功，传输数据到reducer
    dispatch({ type: ORDER_PAY_SUCCESS, payload: data });
  } catch (error) {
    //更新失败
    const message =
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message;
    if (message == "未授权，没有token") {
      dispatch(logout());
    }
    dispatch({
      type: ORDER_PAY_FAIL,
      payload: message,
    });
  }
};

//获取登录用户的所有订单
export const listMyOrders = () => async (dispatch, getState) => {
  try {
    dispatch({ type: ORDER_LIST_MY_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    //获取订单
    const { data } = await axios.get(`/api/orders/myorders`, config);

    //获取成功，传输数据到reducer
    dispatch({ type: ORDER_LIST_MY_SUCCESS, payload: data });
  } catch (error) {
    //获取失败
    dispatch({
      type: ORDER_LIST_MY_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

//更新订单发货状态
export const deliverOrder = (order) => async (dispatch, getState) => {
  try {
    dispatch({ type: ORDER_DELIVER_REQUEST });

    //获取当前登录的用户信息
    const {
      userLogin: { userInfo },
    } = getState();

    // 设置请求头，设置token，使用json字符串发送请求
    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };

    //更新订单
    const { data } = await axios.put(
      `/api/orders/${order._id}/deliver`,
      {},
      config
    );

    //更新成功，传输数据到reducer
    dispatch({ type: ORDER_DELIVER_SUCCESS, payload: data });
  } catch (error) {
    //更新失败
    const message =
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message;
    if (message == "未授权，没有token") {
      dispatch(logout());
    }
    dispatch({
      type: ORDER_DELIVER_FAIL,
      payload: message,
    });
  }
};
